//
//  MSTradeCommentViewController.m
//  SocietySale
//
//  Created by Mike on 16/11/15.
//  Copyright © 2016年 Mike. All rights reserved.
//

#import "MSTradeCommentViewController.h"
#import "MSTradeCommentTableVC.h"

@interface MSTradeCommentViewController ()<UIGestureRecognizerDelegate>
@property (nonatomic, assign) NSInteger             lastIndex;
@property (nonatomic, assign) NSInteger             starIndex;
@property (nonatomic, strong) NSMutableArray        *stateArray;
@property (nonatomic, strong) UILabel               *commentLabel;
@property (nonatomic, strong) UILabel               *reasonlabel;
@property (nonatomic, strong) UIView                *headView;
@property (nonatomic, strong) NSArray               *commentArray;
@property (nonatomic, strong) NSString              *selectReason;
@property (nonatomic, strong) NSString              *editReason;
@property (nonatomic, strong) SXTextView            *remarkTextView;
@property (nonatomic, strong) GXButton              *doneBtn;
@property (nonatomic, strong) MSTradeCommentTableVC *tableVC;
@end

@implementation MSTradeCommentViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    if (!self.isComment) {
        NSArray* viewControllers = [HDUtil checkNilArray:[rootNavigation viewControllers]];
        NSInteger selfIndex = [viewControllers indexOfObject:self];
        if (selfIndex-1>=0) {
            [viewControllers[selfIndex-1] removeFromParentViewController];
        }
    }
}

- (void)initNavigationBar{
    [super initNavigationBar];
    titleLable.text = @"评价";
    leftBarBtn.hidden = NO;
}

- (void)initUI{
    self.tableVC = [[MSTradeCommentTableVC alloc] initWithStyle:UITableViewStyleGrouped];
    self.tableVC.view.frame = self.contentView.bounds;
    self.tableVC.enableRefresh = NO;
    self.tableVC.enableRequest = NO;
    self.tableVC.delegate = (id)self;
    self.tableVC.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.contentView addSubview:self.tableVC.view];
    
    [self layoutHeadView];
    _lastIndex = 0;
    _starIndex = -1;
    _selectReason = @"";
}

- (void)layoutHeadView{
    _headView =[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 135)];
    _headView.backgroundColor = [UIColor whiteColor];
    self.tableVC.tableView.tableHeaderView = _headView;
    
    for (int i = 0; i<5; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake((SCREEN_WIDTH-44*5)/2+i*44, 20, 44, 44);
        btn.tag = 10+i;
        [btn setImage:[UIImage imageNamed:@"star2"] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_headView addSubview:btn];
    }
    
    self.commentLabel =  [self creatLabel:CGRectMake(0, 74, SCREEN_WIDTH, 20)];
    self.commentLabel.textAlignment = NSTextAlignmentCenter;
    self.commentLabel.font = HeitiFont(15);
    self.commentLabel.textColor = kLightBlackColor;
    
    UIView *horizonLineView =[[UIView alloc] initWithFrame:CGRectMake(12, self.commentLabel.bottom+10, SCREEN_WIDTH-24, 0.6)];
    horizonLineView.backgroundColor = kNormalGray;
    [_headView addSubview:horizonLineView];
    
    self.reasonlabel = [self creatLabel:CGRectMake(12, horizonLineView.bottom+8, SCREEN_WIDTH, 20)];
    self.reasonlabel.text = @"请选择原因";
    
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 200)];
    footerView.backgroundColor = kDefaultViewBackgroundColor;
    self.tableVC.tableView.tableFooterView = footerView;
    
    UIView *bgView =[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 110)];
    bgView.backgroundColor = [UIColor whiteColor];
    [footerView addSubview:bgView];
    
    UIView *horizonLineView2 =[[UIView alloc] initWithFrame:CGRectMake(0, bgView.bottom, SCREEN_WIDTH, 0.6)];
    horizonLineView2.backgroundColor = kNormalGray;
    [footerView addSubview:horizonLineView2];
    
    self.remarkTextView = [[SXTextView alloc] initWithFrame:CGRectMake(12, 5, SCREEN_WIDTH-24, 90)];
    self.remarkTextView.font = HeitiFont(14);
    self.remarkTextView.layer.borderColor = kNormalGray.CGColor;
    self.remarkTextView.layer.borderWidth = 1;
    self.remarkTextView.layer.cornerRadius = 2;
    self.remarkTextView.placeholder = @"请填写原因吧~";
    self.remarkTextView.backgroundColor = kDefaultViewBackgroundColor;
    [bgView addSubview:self.remarkTextView];
    
    self.doneBtn = [[GXButton alloc] initWithFrame:CGRectMake(12, bgView.bottom + 25, SCREEN_WIDTH-24, 45)];
    self.doneBtn.titleLabel.font = HeitiFont(16);
    [self.doneBtn setTitle:@"提交评价" forState:UIControlStateNormal];
    [self.doneBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.doneBtn.backgroundColor = kBlueColor;
    self.doneBtn.layer.cornerRadius = 2;
    [self.doneBtn addTarget:self action:@selector(doneClick) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:self.doneBtn];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick)];
    tapGesture.delegate = self;
    [self.contentView addGestureRecognizer:tapGesture];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShownLogin:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHiddenLogin:) name:UIKeyboardWillHideNotification object:nil];
}

//创建label
- (UILabel*)creatLabel:(CGRect)frame{
    UILabel *label = [[UILabel alloc] initWithFrame:frame];
    label.font = HeitiFont(14);
    label.textColor = kDarkGrayColor;
    [_headView addSubview:label];
    return label;
}

- (void)testDataFunc{
    _commentArray = @[@"特别不满意",@"很不满意",@"不太满意",@"比较满意",@"非常满意"];
    self.stateArray = [NSMutableArray arrayWithObjects:@"NO",@"NO",@"NO", nil];
    self.tableVC.stateArray = self.stateArray;
    self.tableVC.dataArray = [@[@"信息不够详细",@"提供信息错误",@"其他原因"] mutableCopy];
}

- (void)updateViewController:(NSNotification *)note {
    NSDictionary *responseDic = note.userInfo;
    if (responseDic[Receiver]==self.VctrID) {
        if (responseDic[@"TradeEvaluate"]!=nil){
            [HDUtil showMessage:@"评价成功"];
            [rootNavigation popViewControllerAnimated:YES];
        }
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_lastIndex != indexPath.row) {
        MSTradeCommentCell *lastCell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:_lastIndex inSection:0]];
        lastCell.imageView.image = [UIImage imageNamed:@"singleselect"];
        [self.stateArray replaceObjectAtIndex:_lastIndex withObject:@"NO"];
    }
    
    MSTradeCommentCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    NSString *state = self.stateArray[indexPath.row];
    if ([state isEqualToString:@"NO"]) {
        cell.imageView.image = [UIImage imageNamed:@"singleselected"];
        [self.stateArray replaceObjectAtIndex:indexPath.row withObject:@"YES"];
    }
    else{
        cell.imageView.image = [UIImage imageNamed:@"singleselect"];
        [self.stateArray replaceObjectAtIndex:indexPath.row withObject:@"NO"];
    }
    
    _lastIndex = indexPath.row;
}

- (void)btnClick:(UIButton*)btn{// 10      14
    for (int i = 0; i<btn.tag-10+1; i++) {
        UIButton *selectedBtn = [_headView viewWithTag:10+i];
        [selectedBtn setImage:[UIImage imageNamed:@"star1"] forState:UIControlStateNormal];
    }
    for (int i = 0; i<14-btn.tag; i++) {
        UIButton *normalBtn = [_headView viewWithTag:btn.tag+1+i];
        [normalBtn setImage:[UIImage imageNamed:@"star2"] forState:UIControlStateNormal];
    }
    self.commentLabel.text = _commentArray[btn.tag-10];
    self.reasonlabel.text = [NSString stringWithFormat:@"您对这条信息给出%ld星评价的原因是",btn.tag-10+1];
    _starIndex = btn.tag - 10;
    if (_starIndex<3) {
        self.tableVC.dataArray = [@[@"信息不够详细",@"提供信息错误",@"其他原因"] mutableCopy];
    }
    else{
        self.tableVC.dataArray = [@[] mutableCopy];
    }
}

- (void)doneClick{
    if (_starIndex < 3) {
        if ([self.stateArray containsObject:@"YES"]) {//有勾选
            if ([_stateArray[0] isEqualToString:@"YES"]) {
                _selectReason = @"vague";
            }
            if ([_stateArray[1] isEqualToString:@"YES"]) {
                _selectReason = @"error";
            }
            if ([_stateArray[2] isEqualToString:@"YES"]) {
                _selectReason = @"other";
            }
            
            if (_starIndex == 1 || _starIndex == 0) {
                NSString *remindLabelStr = [NSString stringWithFormat:@"给出%ld星评价，将会扣除用户对应的江湖币，是否确定提交",_starIndex+1];
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:remindLabelStr delegate:self cancelButtonTitle:@"返回"otherButtonTitles:@"确定提价", nil];
                [alertView show];
            }
            else{
                [self commitComment];
            }
        }
        else{//未勾选
            _selectReason = @"";
            [HDUtil showMessage:@"3星及以下请勾选原因"];
            return;
        }
    }
    else{
        _selectReason = @"";
        [self commitComment];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        [self commitComment];
    }
}

- (void)commitComment{
    NSDictionary *dict = @{
                           @"grade":[NSString stringWithFormat:@"%ld",_starIndex+1],
                           @"reason":self.remarkTextView.text,
                           @"reasonType":_selectReason};
    [netEngine requestTradeEvaluateWithTarget:self.VctrID hudView:self.contentView orderId:_orderId params:dict];
}

- (void)tapClick{
    [self.view endEditing:YES];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([touch.view.superview isKindOfClass:[UITableViewCell class]]) {
        return NO;
    }
    else {
        return YES;
    }
}

//键盘显示的时候的处理
- (void)keyboardWasShownLogin:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    _tableVC.tableView.height = SCREEN_HEIGHT-KNavBarHeight-kbSize.height;
    //    [self updateDataArray];
}

//键盘消失的时候的处理
- (void)keyboardWillBeHiddenLogin:(NSNotification*)aNotification
{
    _tableVC.tableView.height = SCREEN_HEIGHT-KNavBarHeight;
}

@end
